package com.lewis.module.m2.api.tiktok.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lewis.common.core.entity.BaseResult;
import com.lewis.common.core.entity.controller.BaseController;
import com.lewis.module.m2.api.tiktok.domain.TikTok;
import com.lewis.module.m2.api.tiktok.utils.SpiderUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 抖音解析Controller
 *
 * @author Lewis 2021-09-10
 */
@Api(tags = "抖音服务")
@RestController
@RequestMapping("/tikTok")
public class TikTokController extends BaseController {

	@ApiOperation("获取抖音无水印视频url列表")
	@GetMapping("/getNoWatermarkVideoUrlList")
	public BaseResult getNoWatermarkVideoUrlList(String shareUrl) {
		List<TikTok> tikTokList = getTikTokList(shareUrl);
		List<String> noWatermarkVideoUrlList = new ArrayList<>();
		tikTokList.forEach(tikTok -> noWatermarkVideoUrlList.add(tikTok.getNoWatermarkUrl()));
		return BaseResult.ok().setData(noWatermarkVideoUrlList);
	}

	@ApiOperation("获取抖音无水印图集url列表")
	@GetMapping("/getNoWatermarkImageUrlList")
	public BaseResult getNoWatermarkImageUrlList(String shareUrl) {
		List<TikTok> tikTokList = getTikTokList(shareUrl);
		List<String> noWatermarkImageUrlList = new ArrayList<>();
		tikTokList.forEach(tikTok -> noWatermarkImageUrlList.addAll(tikTok.getPhotos()));
		return BaseResult.ok().setData(noWatermarkImageUrlList);
	}

	/**
	 * 获取信息
	 *
	 * @param shareStr 抖音分享的信息
	 * @return 结果
	 */
	public List<TikTok> getTikTokList(String shareStr) {
		List<TikTok> list = new ArrayList<>();
		String url = "https://v.douyin.com/" + SpiderUtil.regexMatch(shareStr, "douyin.com/(.*?)/");
		String src = SpiderUtil.requireUrl(url).url().toString();
		// 提取URL中视频id
		String id = SpiderUtil.regexMatch(src, "video/(.*?)/");
		if (id != null) {
			// 拼接并请求接口
			String jk = "https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=" + id;
			JSONArray itemList = JSON.parseObject(SpiderUtil.requireUrl(jk).body()).getJSONArray("item_list");
			itemList.forEach(item -> {
				list.add(setTikTokInfo(JSON.parseObject(item.toString())));
			});
		}
		return list;
	}

	/**
	 * 提取JSON中相关信息.
	 *
	 * @param json json
	 * @return 结果
	 */
	public TikTok setTikTokInfo(JSONObject json) {
		TikTok tikTok = new TikTok();
		tikTok.setTitle(json.getString("desc"));
		tikTok.setAuthor(json.getJSONObject("author").getString("nickname"));
		tikTok.setCommentCount(json.getJSONObject("statistics").getLong("comment_count"));
		tikTok.setDiggCount(json.getJSONObject("statistics").getLong("digg_count"));
		tikTok.setShareCount(json.getJSONObject("statistics").getLong("share_count"));
		// 提取图片，如果有图片，则没有视频
		JSONArray images = json.getJSONArray("images");
		if (images != null && images.size() > 0) {
			tikTok.setPhotos(extractImagesFromJsonArray(images, "url_list"));
		} else {
			String noWatermarkUrl = json.getJSONObject("video").getJSONObject("play_addr").getJSONArray("url_list").getString(0).replaceAll("playwm", "play");
			if (!noWatermarkUrl.contains("obj")) {
				tikTok.setNoWatermarkUrl(noWatermarkUrl);
			}
		}

		JSONObject music = json.getJSONObject("music");
		if (music != null) {
			tikTok.setMusicTitle(music.getString("title"));
			tikTok.setMusicUrl(music.getJSONObject("play_url").getString("uri"));
		}
		return tikTok;
	}

	/**
	 * 从JsonArray中提取url.
	 *
	 * @param jsonArray the json array
	 * @return the list
	 */
	private List<String> extractImagesFromJsonArray(JSONArray jsonArray, String targetStr) {
		List<String> images = new LinkedList<>();
		for (Object object : jsonArray) {
			JSONObject imageObj = (JSONObject) object;
			images.add(imageObj.getJSONArray(targetStr).get(3).toString());
		}
		return images;
	}
}
